#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import pymysql
import datetime
import traceback


def get_mdb_conn(my_host, my_user, my_password, my_port, my_db):
    dbconn = None
    ok_flag = True
    msg_sb = ''
    try:
        dbconn = pymysql.connect(host=my_host, user=my_user, passwd=my_password, port=my_port, db=my_db, charset='utf8')
    except Exception as err:
        ok_flag = False
        msg_sb = 'get_mdb_conn connect error:{0}'.format(err)
    return dbconn, ok_flag, msg_sb


def execute_sql(db_cursor, sql):
    try:
        db_cursor.execute(sql)
    except Exception as e:
        if e.args[0] != 1062:
            print(sql)
            print(traceback.format_exc())
    return


if __name__ == "__main__":

    tz_host = '172.26.249.246'
    tz_port = 3306
    tz_user = 'md'
    tz_password = 'maida6868'
    tz_db = 'scrapy'
    mdb, ok, m_msg = get_mdb_conn(tz_host, tz_user, tz_password, tz_port, tz_db)
    if not ok:
        print('invalid mysql {0}'.format(m_msg))
        sys.exit(-1)

    now_time = datetime.datetime.now()
    pre_time = now_time + datetime.timedelta(days=-7)
    start_time = pre_time.strftime('%Y-%m-%d %H:%M:%S')
    with mdb.cursor() as m_cursor:
        m_sql = "select comp_name from company_code where update_time >= '{0}'".format(start_time)
        execute_sql(m_cursor, m_sql)
        rows = m_cursor.fetchall()
        with open('./file/scrapy_db_company.txt', 'w', encoding='utf-8') as fp:
            for row in rows:
                fp.write(row[0] + '\n')
